package org.brownflat.lighthouse.monitoring.ci;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;
import org.brownflat.lighthouse.util.StringUtil;

import java.io.IOException;

public abstract class HTTPServer {
    private static final Logger LOG = Logger.getLogger(HTTPServer.class);

    private String host;
    private int port;
    private String path = "";
    private boolean ssl = false;

    public HTTPServer(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public HTTPServer(String host, int port, String path) {
        this.host = host;
        this.port = port;
        this.path = path;
    }

    public void setSsl(boolean ssl) {
        this.ssl = ssl;
    }

    public String execute(HTTPRequest request) throws ConnectionException {
        String fullUrl = getFullURL(request);
        HttpMethod method = new GetMethod(fullUrl);
        method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
        HttpClient client = new HttpClient();

        LOG.debug("Requesting URL from server: " + fullUrl);
        return execute(method, client);
    }

    private String getFullURL(HTTPRequest request) {
        return getUrl() + "/" + request.getURI();
    }

    private String execute(HttpMethod method, HttpClient client) throws ConnectionException {
        try {
            int code = client.executeMethod(method);
            if (code != 200) {
                throw new ConnectionException("HTTP Response Code: " + code);
            }
            return StringUtil.toString(method.getResponseBodyAsStream()).replace("\n", "");
        } catch (HttpException e) {
            throw new ConnectionException(e);
        } catch (IOException e) {
            throw new ConnectionException(e);
        }
    }

    public String getUrl() {
        return (ssl ? "https://" : "http://") + host + ":" + port + (StringUtil.isEmpty(path) ? "/" : "/" + path + "/");
    }
}
